import React, { useState, useEffect } from "react"
import PubSub, { publish } from "pubsub-js"
import Header from "./components/Header/Header"
import List from "./components/List/List"
import Item from "./components/Item/Item"
import Footer from "./components/Footer/Footer"

import "./App.css"
export default function App() {
  const [list, setList] = useState(
    JSON.parse(localStorage.getItem("todos")) || []
  )

  useEffect(() => {
    const addTodoId = PubSub.subscribe("add", (topic, todoName) => {
      const todo = {
        id: Date.now(),
        todoName,
        isDone: false,
      }
      setList((list) => {
        const newList = [...list]
        newList.push(todo)
        return newList
      })
    })

    const updateCheckId = PubSub.subscribe("updateIsDone", (topic, id) => {
      setList((list) => {
        const newList = [...list]
        newList.forEach((item) => {
          if (item.id === id) item.isDone = !item.isDone
        })
        return newList
      })
    })

    const allCheckId = PubSub.subscribe("allIsDone", (topic, isDone) => {
      setList((list) => {
        const newList = [...list]
        newList.forEach((item) => {
          item.isDone = isDone
        })
        return newList
      })
    })

    const deleteTodoId = PubSub.subscribe("deleteTodo", (topic, id) => {
      setList((list) => {
        const newList = list.filter((item) => item.id !== id)
        return newList
      })
    })

    const editTodoId = PubSub.subscribe("editTodo", (topic, data) => {
      const [newTodoName, id] = data
      setList((list) => {
        const newList = [...list]
        newList.forEach((item) => {
          if (item.id === id){
            item.todoName = newTodoName
            item.isDone = false
          }
        })
        return newList
      })
    })

    const deleteDoneId = PubSub.subscribe(
      "deleteIsDone",
      (topic, newList) => {
        setList((list) => {
          return newList
        })
      }
    )

    return () => {
      PubSub.unsubscribe(addTodoId)
      PubSub.unsubscribe(updateCheckId)
      PubSub.unsubscribe(allCheckId)
      PubSub.unsubscribe(deleteTodoId)
      PubSub.unsubscribe(editTodoId)
      PubSub.unsubscribe(deleteDoneId)
    }
  }, [])

  localStorage.setItem("todos", JSON.stringify(list))

  return (
    <div className="todo-container">
      <div className="todo-wrap">
        <Header></Header>
        <div>
          <List>
            {list.map((item) => {
              return <Item key={item.id} todo={item}></Item>
            })}
          </List>
          {list.length ? <Footer list={list}></Footer> : <h1>暂无数据</h1>}
        </div>
      </div>
    </div>
  )
}
